function fd = serial2frac(sd)
%serial2frac - Serial to fractional year conversion
%
%       FD = serial2frac(SD)
%
% Let SD be a date vector in MATLAB serial date format. This function 
% computes the corresponding vector of fractional year dates, i.e. a date 
% vector whose values are expressed in standard decimal part of a year 
% yyyy.ddddd (e.g., 732314, which corresponds to 2-Jan-2005, is converted 
% into 2005+1/365 = 2005.00274).
%
% See also date2gpsw, gpsw2serial, frac2serial, frac2MJD, MJD2frac, 
% serial2YMD, leapy.

% G. Teza, 2021

sd = sd(:);                 % to have a column vector

dv = datevec(sd);
nr = size(dv,1);
if size(dv,2) > 3           % first day of the year
    jdc = datenum([dv(:,1) ones(nr,2) dv(:,4) zeros(nr,2)]); 
else
    jdc = datenum([dv(:,1) ones(nr,2)]);
end
nd = datenum(dv)-jdc;       % julian day of the year (1-Jan: 0-day)"

Ily = leapy(dv(:,1));
denom = 365*ones(nr,1);
denom(Ily) = 366;
if size(dv,2) > 3
    dy = (nd+dv(:,4)/24)./denom;
else
    dy = nd./denom;
end

fd = dv(:,1)+dy;